import request from "./request";
import COS from "cos-js-sdk-v5";

function uuid(len = 8) {
  const characters =
    "0123456789ABCDEFGHIJK12134567895LMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  for (let i = 0; i < len; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

function fetchSmart({ url, data, method = "post", headers }) {
  const form = {
    url,
    method,
  };
  if (method === "get") {
    form.params = data || {};
  } else {
    form.data = data || {};
  }

  if (headers) {
    form.headers = headers;
  }

  return new Promise((resolve) => {
    request(form)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        resolve(err);
      });
  });
}

fetchSmart.get = (url, data) => {
  return fetchSmart({ url, data, method: "get" });
};

fetchSmart.post = (url, data) => {
  return fetchSmart({ url, data, method: "post" });
};


function uploadFileToCOS(file, path, bucket, region, stsInfo, callbacks = {}) {
  return new Promise((resolve, reject) => {
    const { credentials, startTime, expiredTime } = stsInfo.data;

    const cos = new COS({
      getAuthorization(options, callback) {
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          SecurityToken: credentials.sessionToken,
          StartTime: startTime,
          ExpiredTime: expiredTime, // 时间戳，单位秒
        });
      },
    });
    const fileSize = file.size;
    const totalSizeMB = parseFloat((fileSize / (1024 * 1024)).toFixed(2));

    cos.uploadFile(
      {
        Bucket: bucket,
        Region: region,
        Key: path,
        Body: file,
        SliceSize: 1024 * 1024 * 10,
        onProgress: function (info) {
          var percent = parseInt(info.percent * 10000) / 100;
          var speed = parseInt(info.speed / 1024 / 1024 * 100) / 100;
          callbacks.onProgress && callbacks.onProgress(percent, speed, totalSizeMB)

          console.log(`进度：${percent}%; 速度：${speed}Mb/s; 已上传：${uploadedSizeMB} MB; 总大小：${totalSizeMB} MB`);
        },
        onFileFinish: function (err, data, options) {
          callbacks.onFileFinish && callbacks.onFileFinish(options.Key + '上传' + (err ? '失败' : '完成'))

        },
      },
      (err, data) => {
        if (err) {
          console.error("Upload failed:", err);
          reject(err);
        } else {
          console.log("Upload successful:", data);
          resolve(data);
        }
      }
    );
  });
}

fetchSmart.cosUplod = async (fileOrBlob, prefix, callbacks) => {
  const isDev = window.location.host.indexOf("localhost") > -1;
  try {
    const stsInfo = await fetchSmart.post("/api/cos-sts-pc");
    const { bucket, region } = stsInfo.data;
    let file = fileOrBlob instanceof File ? fileOrBlob : new File([fileOrBlob], `${uuid()}`, { type: fileOrBlob.type || 'application/octet-stream' });

    let path = `${prefix}/${file.name}`;
    if (!isDev) {
      path = `${prefix}/${uuid()}-${file.name}`;
    }

    const res = await uploadFileToCOS(file, path, bucket, region, stsInfo, callbacks);
    if (res.Location) {
      return "https://" + res.Location;
    } else {
      return Promise.reject(res);
    }
  } catch (error) {
    console.error("An error occurred during the upload:", error);
  }
};


export default fetchSmart;
